/**
 * ConsoleFrame.java
 * @author: liuex
 * 2008-1-8 ����03:27:24
 *
 * note: 
 */
package fun.ui.frames;

import java.io.IOException;
import java.io.StringReader;

import console.ui.ConsoleListener;
import console.ui.TextPaneConsole;
import fun.parser.EvaluationException;
import fun.parser.LexerException;
import fun.parser.ast.AstParser;
import fun.parser.ast.node.base.Expression;
import fun.parser.postfix.PostfixParser;
import fun.parser.postfix.PostfixProgram;
import fun.symtable.UserSymbolTable;
import fun.ui.FunMainFrame;

public class ConsoleFrame extends BasicInternalFrame implements ConsoleListener {
	private TextPaneConsole console = null;
	private AstParser ast = new AstParser();
	private PostfixParser postfix = new PostfixParser();

	public ConsoleFrame(FunMainFrame mainframe) {
		super(mainframe);
		this.initialize();
	}

	public void execute(String input) {
		try {
			postfix.setSource(new StringReader(input));
			PostfixProgram exp = null;
			exp = postfix.parse();
			Expression expr = ast.parse(exp);
			double val = expr.getValue(UserSymbolTable.getInstance());
			console.print(getIndent()).println(val);
		} catch (IOException e) {
			console.error("IO failed: " + e.getLocalizedMessage());
			e.printStackTrace();
		} catch (LexerException e) {
			console.error("Lexer failed: " + e.getLocalizedMessage());
			e.printStackTrace();
		} catch (EvaluationException e) {
			console.error("Evalue failed: " + e.getLocalizedMessage());
			e.printStackTrace();
		}
		console.print(this.getPrompt());
	}

	private String getPrompt() {
		return "fun>";
	}

	private String getIndent() {
		return "\t";
	}

	private void initialize() {
		this.setTitle("Console");
		this.setContentPane(this.getConsole());
	}

	private TextPaneConsole getConsole() {
		if (null == console) {
			console = new TextPaneConsole();
			console.addConsoleListener(this);
			console.print(this.getPrompt());
		}
		return console;
	}
}
